<?php
// +----------------------------------------------------------------------
// | 悟空信息技术有限公司
// +----------------------------------------------------------------------
// | Copyright (c)2016 http://www.wkidt.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: wkidt team Tx <admin@wkidt.com> 2018/5/12 11:32
// +----------------------------------------------------------------------
// | Readme: 预约模型
// +----------------------------------------------------------------------


namespace  app\admin\model;

use think\Db;
use think\exception\DbException;
use Wkidt\think5\model\Model;
use EasyWeChat\Factory;

class AppointmentModel extends Model
{

    /**
     * 获取预约时间
     * @param $shop_id
     * @return array
     * @throws \think\exception\PDOException
     */
    public  function  getAppointmentDate($shop_id){

        if(empty($shop_id)){
            return ['code' => 'ERROR', 'info' =>'没有店铺id'];
        }

        $d_time=strtotime(date('Y-m-d'));//当天的时间戳
        $this->automationAddAppointmentDate($shop_id,$d_time);//自动添加预约时间

       $appointment_date=Db::name('appointment_date')->where(['shop_id'=>$shop_id,'a_date'=>['egt',$d_time]])->select();
        return ['info' =>'获取预约时间成功！','data'=> $appointment_date];
    }


    /**
     * 获取预约时间的点位
     * @param $ad_id
     * @return array
     */
    public  function  getAppointmentDateDot($ad_id){

        if(empty($ad_id)){
            return ['code' => 'ERROR', 'info' =>'没有预约时间id'];
        }

        $appointment_date_da=Db::name('appointment_date_dot')->where(['a_date_id'=>$ad_id])->select();
        return ['info' =>'获取预约时间成功！','data'=> $appointment_date_da];

    }

    /**
     * 添加预约项目
     * @param $ad_id
     * @return array
     */
    public  function  addAppointmentProject($data){
        $data['add_time'] = time();
        $res['data'] = Db::name('appointment_date_dot')->strict(true)->insertGetId($data);

        if($res){
            return $res;
        }else{
            return null;
        }


    }

    /**
     * 删除预约项目
     * @param $ad_id
     * @return array
     */
    public  function  deleteAppointmentProject($dot_id){

        $res['data'] = Db::name('appointment_date_dot')->where('dot_id',$dot_id)->delete();
        if($res['data']){
            return $res;
        }else{
            return null;
        }
    }

    /**
     * 取消预约预约
     * @param $ad_id
     * @return array
     */
    public  function  cancelAppointment($ma_id){
        $dot_id = Db::name('member_appointment')->where('ma_id',$ma_id)->value('dot_id');

        Db::name('appointment_date_dot')->where('dot_id',$dot_id)->setDec('already_appointment');

        $res['data'] = Db::name('member_appointment')->where('ma_id',$ma_id)->delete();

        if($res['data']){
            return $res;
        }else{
            return null;
        }


    }

    /**
     * 修改预约项目
     * @param $ad_id
     * @return array
     */
    public  function  setAppointmentProject($data){
        $data['add_time'] = time();
        $res['data'] = Db::name('appointment_date_dot')->update($data);
        if($res['data']){
            return $res;
        }else{
            return null;
        }


    }



    /**
     * 修改预约次数
     * @param $dot_id
     * @param $appointment_sum
     * @return array
     */
    public  function  setAppointmentNumber($dot_id,$already_appointment){

        if(empty($dot_id)){
            return ['code' => 'ERROR', 'info' =>'没有预约点位id'];
        }

       if(Db::name('appointment_date_dot')->where(['dot_id'=>$dot_id])->update(['already_appointment'=>$already_appointment])){
           return ['code' => 'SUCCESS', 'info' =>'修改成功！'];
       }else{
           return ['code' => 'ERROR', 'info' =>'修改失败'];
       }


    }



    /**
     * 自动添加预约时间
     * @param $shop_id
     * @return array
     * @throws \think\exception\PDOException
     */
    private  function  automationAddAppointmentDate($shop_id,$d_time){

        $appointment_date=Db::name('appointment_date')->where(['shop_id'=>$shop_id,'a_date'=>['egt',$d_time]])->select();
        $sum=count($appointment_date);
        if($sum<7){
            if($sum==0){
                $a_date=$d_time;
            }else {
                $a_date = $appointment_date[$sum - 1]['a_date']+(24*60*60);
            }

            for($i=$sum;$i<=6;$i++){
                if($i>$sum){
                    $a_date =$a_date+(24*60*60);
                }
                $data['shop_id']=$shop_id;
                $data['a_date']=$a_date;
                $data['add_time']=time();
                Db::name('appointment_date')->insert($data);
            }
        }

    }

    /**
     *添加用户预约
     */
    public  function  addMemberAppointment($item){

        $member = Db::name('member')->where('member_card',$item['member_card'])->find();
        if($member){
            $item['status']=1;
            $item['uid']=$member['uid'];
            $item['openid']=$member['openid'];
            $item['shop_id']=1;
            $item['check_status']=0;
            $item['add_time']=time();

            $res= Db::name('member_appointment')->strict(true)->insertGetId($item);
            $appointment_date_dot = Db::name('appointment_date_dot')->where('dot_id',$item['dot_id'])->find();

            if ($appointment_date_dot['appointment_sum'] > $appointment_date_dot['already_appointment']){

                $already_appointment=$appointment_date_dot['already_appointment']+1;
                $this->setAppointmentNumber($item['dot_id'],$already_appointment);
            }else{
                return ['code' => 'ERROR', 'info' =>'预约满了','data' =>array()];
            }

            if($res){
                $memberInfo = $member;
                // 推送模版消息
                $app = Factory::officialAccount(config("EasyWechetConfig"));
                $rs = $app->template_message->getPrivateTemplates();

                $sent_data['touser'] = $memberInfo['openid'];
                $sent_data['template_id'] = 'Y8pfWNYbeeSgnNutd63t2Es9OhSNIv7n0s84rfGhpkY';
                $sent_data['url'] = 'http://oscar.wkidt.com/#/';
                $sent_data['data']['first'] = "您卡号为".$memberInfo['member_card']."的会员卡预约成功";
                $sent_data['data']['keyword1'] =$appointment_date_dot['title'];
                $sent_data['data']['keyword2'] = '课程时间：'.date("Y-m-d", $appointment_date_dot['daytimes']).' : '.$appointment_date_dot['startTime'].'-'.$appointment_date_dot['endTime'];
                $sent_data['data']['remark'] = '奥斯卡全体员工期待您的光临';

                $app->template_message->send($sent_data);
                return ['data' =>$res,];
            }else{
                return ['code' => 'ERROR', 'info' =>'没有数据','data' =>array()];
            }
        }else{
            return ['code' => 'ERROR', 'info' =>'会员卡不存在','data' =>array()];
        }
    }



    /**
     *获取用户预约列表
     */
    public  function  getMemberAppointment($query){

        if($query['ad_id']){
            $where['ma.ad_id'] = $query['ad_id'];
        }
        if($query['uid']){
            $where['ma.uid'] = $query['uid'];
        }
        $today = strtotime(date("Y-m-d"),time());

        try {
            $list = Db::name('member_appointment')
                ->alias('ma')
                ->join('wk_appointment_date_dot dot', 'ma.dot_id = dot.dot_id', 'left')
                ->join('wk_product p', 'p.id = dot.product_id', 'left')
                ->join('wk_member member', 'member.uid = ma.uid', 'left')
                ->where($where)
                ->where('ma.status', 1)
                ->where('dot.daytimes', '>=', $today)
                ->order(['ma.ma_id' => 'desc'])
                ->field('ma.ma_id,ma.uid,ma.status,ma.check_status,ma.add_time,p.title as title,p.price,p.type,p.weekend_price,p.num,p.key_name,dot.title as dot_title,dot.startTime,dot.endTime,dot.daytimes,member.realName,member.phone,member.member_group_title,member.member_card')
                ->paginate();
        } catch (DbException $e) {
        }

        $data=$list->items();
        if($data){
            return ['data' =>$data, 'page' => $list->getPageInfo()];
        }else{
            return ['data' =>$data];
        }
    }


}